/* eslint-disable no-extend-native */

import Big from './big.js';

Number.prototype.originToFixed = function (digit) {
  return new Big(this).toFixed(digit);
};
/**
 * 千分位格式化
 * @param {Number} [digit] - 位数
 * @param {Boolean} [round] - 是否四舍五入
 * @return {string}
 */
Number.prototype.toFixed = function (digit, round) {
  try {
    if (round) {
      return this.originToFixed(digit);
    }
    const num = new Big(this);
    const _join = (len) => [...new Array(len)].map(() => 0).join('');
    const _calc = (v) => {
      if (v.includes('.')) {
        const [a, b] = v.split('.');
        if (digit <= 0) {
          return a;
        } else {
          return a + '.' + b.substr(0, digit || b.length) + _join(digit - b.length > 0 ? digit - b.length : 0);
        }
      } else {
        return digit > 0 ? num + '.' + _join(digit) : num + '';
      }
    };

    if (/e/i.test(num.toString())) {
      return _calc(num.toFixed());
    } else {
      return _calc(num.toString());
    }
  } catch {
    return this;
  }
};

/**
 * 获取小数点位数
 * @returns {number}
 */
Number.prototype.floatLength = function () {
  try {
    const str = String(this);
    if (str.includes('.')) {
      return str.split('.')[1].length;
    } else {
      return 0;
    }
  } catch {
    return 0;
  }
};

/**
 * 千分位格式化
 * @param {Number} [digit] - 位数
 * @param {Boolean} [round] - 是否四舍五入
 * @return {string}
 */
Number.prototype.toFormat = function (digit = 2, round) {
  try {
    if (digit === 'all') digit = undefined;
    const _this = !round ? this.toFixed(digit) : this.originToFixed(digit);
    if (_this.includes('.')) {
      let [a, b] = _this.split('.');
      a = Number(a).toLocaleString('zh');
      if (digit === 0) return a;
      return a + '.' + b;
    }
    return Number(_this).toLocaleString('zh');
  } catch {
    return this;
  }
};

// 加法
Number.prototype.add = function (arg) {
  try {
    const a = new Big(this);
    const b = new Big(arg);
    return a.plus(b).toNumber();
  } catch {
    return Number(this) + Number(arg);
  }
};

// 减法
Number.prototype.sub = function (arg) {
  try {
    const a = new Big(this);
    const b = new Big(arg);
    return a.minus(b).toNumber();
  } catch {
    return Number(this) - Number(arg);
  }
};

// 乘法
Number.prototype.mul = function (arg) {
  try {
    const a = new Big(this);
    const b = new Big(arg);
    return a.times(b).toNumber();
  } catch {
    return Number(this) * Number(arg);
  }
};

// 除法
Number.prototype.div = function (arg) {
  try {
    const a = new Big(this);
    const b = new Big(arg);
    return a.div(b).toNumber();
  } catch {
    return Number(this) / Number(arg);
  }
};
